package com.ywjt.platformbusiness.classify.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cy.tablayoutniubility.FragPageAdapterVp2;
import com.cy.tablayoutniubility.TabAdapter;
import com.cy.tablayoutniubility.TabLayoutScroll;
import com.cy.tablayoutniubility.TabMediatorVp2;
import com.cy.tablayoutniubility.TabViewHolder;
import com.stx.xhb.xbanner.XBanner;
import com.ywjt.platformbusiness.EventBusBean;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.classify.adapter.GoodsTypeAdapter;
import com.ywjt.platformbusiness.classify.fragment.ShopHomeGoodsFragment;
import com.ywjt.platformbusiness.classify.model.ShopListModel;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.store.model.GoodsClassOneModel;
import com.ywjt.platformbusiness.store.model.StoreSecondClassifyModel;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.PictureUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ShopHomeDetailActivity  extends BaseActivity implements View.OnClickListener {
    private XBanner banner;
    private List<Integer> banners;
    private PopupWindow popupWindow;
    private ImageView ivBack,ivShopLogo;
    private TextView tvShopAddress,tvShopName,tvDistance;

    private ViewPager2 viewpager;
    private TabLayoutScroll tab1;
    private  ShopListModel.ResultDTO.RecordsDTO shopModel;

    public static void actionStart(Context context, ShopListModel.ResultDTO.RecordsDTO shopModel) {
        Intent intent = new Intent(context, ShopHomeDetailActivity.class);
        intent.putExtra("shopModel",(Serializable) shopModel);
        context.startActivity(intent);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(false);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.shop_home_detail_activity;
    }

    @Override
    protected void initView() {
        shopModel=(ShopListModel.ResultDTO.RecordsDTO)getIntent().getSerializableExtra("shopModel");
        banner=findViewById(R.id.banner);
        tab1=findViewById(R.id.tab1);
        tvShopAddress=findViewById(R.id.tvShopAddress);
        ivBack=findViewById(R.id.ivBack);
        ivShopLogo=findViewById(R.id.ivShopLogo);
        tvDistance=findViewById(R.id.tvDistance);
        tvShopName=findViewById(R.id.tvShopName);
        viewpager=findViewById(R.id.viewpager);
        ivBack.setOnClickListener(this::onClick);
        banners=new ArrayList<>();
        banners.add(R.mipmap.icon_home_default_banner);
        banners.add(R.mipmap.icon_home_default_banner);
        banners.add(R.mipmap.icon_home_default_banner);
        banners.add(R.mipmap.icon_home_default_banner);
        banner.setData(R.layout.item_banner1,banners,null);
        banner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object object, View view, int position) {
                RelativeLayout container=(RelativeLayout) view;
                ImageView ivBanner=container.findViewById(R.id.ivBanner);
                Glide.with(ShopHomeDetailActivity.this).
                        load(banners.get(position)).into(ivBanner);
            }
        });


        if (shopModel!=null){
            setTopView();
        }
        getTypeData();
    }
    //设置上步商铺信息
    public void setTopView(){
        tvShopAddress.setText(shopModel.getAddress());
        Glide.with(ShopHomeDetailActivity.this).load(shopModel.getShopLogo())
                .placeholder(R.mipmap.default_headlink)
                .apply(new RequestOptions().transform(new PictureUtils()))
                .into(ivShopLogo);
        tvShopName.setText(shopModel.getShopName());
        tvDistance.setText("距我："+(shopModel.getDistance()==null?"0":shopModel.getDistance())+"米");
    }

    public void showPopu(View view,List<StoreSecondClassifyModel.ResultDTO> data){
        View inflate = LayoutInflater.from(getContext()).inflate(R.layout.dialog_goods_type_select,null);
        GoodsTypeAdapter adapter=new GoodsTypeAdapter(data);
        RecyclerView rcCommon=inflate.findViewById(R.id.rcCommon);
        rcCommon.setLayoutManager(new GridLayoutManager(ShopHomeDetailActivity.this,4,RecyclerView.VERTICAL,false));
        rcCommon.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                EventBusBean busBean=new EventBusBean();
                busBean.setCode(20);
                busBean.setMsg(data.get(position).getId());
                EventBus.getDefault().post(busBean);
            }
        });
        popupWindow = new PopupWindow(inflate, RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.WRAP_CONTENT);
        //设置背景,这个没什么效果，不添加会报错
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        /**背景阴影*/
        //ColorDrawable dw = new ColorDrawable(0x33000000);
        // popupWindow.setBackgroundDrawable(dw);
        //设置点击弹窗外隐藏自身
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        //相对于某一个控件的位置
        popupWindow.showAsDropDown(view,0,0);
    }


    private void getTypeData() {
        new HttpRequest(getContext()).doGet(UrlConstants.getShopFirstClassList+shopModel.getId(), "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), GoodsClassOneModel.class);
                        if (obj instanceof GoodsClassOneModel) {
                            GoodsClassOneModel model = (GoodsClassOneModel) obj;
                            if (model.getResult().size()>0){
                                FragPageAdapterVp2<String> fragmentPageAdapter = new FragPageAdapterVp2<String>(ShopHomeDetailActivity.this) {

                                    @Override
                                    public Fragment createFragment(String bean, int position) {
                                        ShopHomeGoodsFragment orderFragment = ShopHomeGoodsFragment.newInstance(0,model.getResult().get(position).getId(),shopModel.getId());
                                        return orderFragment;
                                    }

                                    @Override
                                    public void bindDataToTab(TabViewHolder holder, int position, String bean, boolean isSelected) {
                                        TextView textView = holder.getView(R.id.tv);
                                        if (isSelected) {
                                            textView.setTextColor(0xffFB222A);
                                            textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                                            if (position!=0){
                                                getAllTypeData(model.getResult().get(position).getId());
                                            }
                                        } else {
                                            textView.setTextColor(0xff333333);
                                            textView.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                                        }
                                        textView.setText(bean);
                                    }

                                    @Override
                                    public int getTabLayoutID(int position, String bean) {
                                        return R.layout.tab_item;
                                    }
                                };

                                TabAdapter<String> tabAdapter = new TabMediatorVp2<String>(tab1, viewpager).setAdapter(fragmentPageAdapter);
                                List<String> list = new ArrayList<>();
                               for (int i=0;i<model.getResult().size();i++){
                                   list.add(model.getResult().get(i).getName());
                               }
                                fragmentPageAdapter.add(list);
                                tabAdapter.add(list);
                            }
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getAllTypeData(String commodityId) {
        new HttpRequest(getContext()).doPost(UrlConstants.getUnderClassifyByCommodityId+commodityId, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), StoreSecondClassifyModel.class);
                        if (obj instanceof StoreSecondClassifyModel) {
                            StoreSecondClassifyModel model = (StoreSecondClassifyModel) obj;
                            if (model.getResult().size()>0){
                                showPopu(tab1,model.getResult());
                            }
                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void initData() { }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return TITLEBAR_NULL;
    }
}